package com.bls.cate.ui.activity.write_article;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bls.blslib.base.BaseActivity;
import com.bls.cate.R;
import com.bls.cate.adapter.WriteImageAdapter;
import com.bls.cate.constant.EnumCode;
import com.bls.cate.constant.IntentCode;
import com.bls.cate.listener.EditTextChangedListener;
import com.bls.cate.model.LoginSpRes;
import com.bls.cate.service.UploadArticleImageService;
import com.bls.cate.ui.widget.TitleView;
import com.bls.cate.utils.AccountUtil;
import com.bls.cate.utils.GlideImageLoader;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;

import java.util.ArrayList;

/**
 * 　　  () 　　　  ()
 * 　　  ( ) 　　　( )
 * 　　  ( ) 　　　( )
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　┻　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ——————————————————
 * Created by BinglingSu on 2018/2/5.
 */

public class WriteArticleActivity extends BaseActivity implements EditTextChangedListener.WriteTitleListener, BaseQuickAdapter.OnItemClickListener {
    public static String SERVICE_RECEIVER = "com.bls.cate.ui.activity.write_article.WriteArticleActivity";
    private TitleView titleView;
    private TextView tvTitleNum, btnAlignLeft, btnAlignCenter, btnAlignRight;
    private EditText etTitle, etContent;
    private RecyclerView rvImage;
    private TextView btnOver;
    private WriteArticleActivity mActivity;

    private String uniqueId;
    private String currentTime = String.valueOf(System.currentTimeMillis());//当前文章的时间戳
    private String publishName; //文章的名称
    public static final int REQUEST_CODE_SELECT = 100, REQUEST_CODE_PREVIEW = 101;
    ArrayList<ImageItem> tempWriteImages = null;                            //临时图片数组
    ArrayList<ImageItem> hasSelectPublishImages = new ArrayList<>();         //已选择的图片数组
    private int maxImgCount = 99;               //允许选择图片最大数
    private WriteImageAdapter writeImageAdapter;
    private ImageItem endImageItem;                                         //已选择的图片数组的最后一个Item
    private EnumCode.ArticleAlignEnum alignEnum = EnumCode.ArticleAlignEnum.LEFT;  //文章对齐方式
    private BroadcastReceiver myReceiver;
    private LoginSpRes loginSpRes;
    private MaterialDialog publishLoadingDialog;

    @Override
    protected void initRoot() {
        super.initRoot();
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SERVICE_RECEIVER);
        registerReceiver(myReceiver, intentFilter);
        loginSpRes = AccountUtil.getStrLoginSp();

        // MaterialDialog loadingDialog = new MaterialDialog(getActivity());
        MaterialDialog.Builder builder = new MaterialDialog.Builder(this).content("发布中,请稍等......").progress(true, 0);
        publishLoadingDialog = builder.build();
    }

    @Override
    protected void initParams() {
        super.initParams();
        uniqueId = AccountUtil.getUniqueId();
        publishName = "Publish_".concat(currentTime).concat("_").concat(uniqueId);
        tempWriteImages = null;
        mActivity = (WriteArticleActivity) getActivity();
        initImagePicker();
        endImageItem = new ImageItem();
        endImageItem.name = "AddTempImage";
        hasSelectPublishImages.add(endImageItem);
        writeImageAdapter = new WriteImageAdapter(hasSelectPublishImages);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_write;
    }

    @Override
    protected void initFvb() {
        titleView = findViewById(R.id.title_view);
        tvTitleNum = findViewById(R.id.tv_title_num);
        etTitle = findViewById(R.id.et_title);
        etContent = findViewById(R.id.et_content);
        rvImage = findViewById(R.id.rv_image);
        btnOver = findViewById(R.id.btn_over);

        btnAlignLeft = findViewById(R.id.btn_align_left);
        btnAlignCenter = findViewById(R.id.btn_align_center);
        btnAlignRight = findViewById(R.id.btn_align_right);
    }

    @Override
    protected void initTitle() {
        titleView.setTitleMiddleText("发表");
        titleView.setTitleRightText("更多");
        titleView.setBtnMode(1, 2);
        titleView.setTitleClickListener(new TitleView.OnTitleClickListener() {
            @Override
            public void onTitleClick(int btnType) {
                if (btnType == 1)
                    mActivity.finish();
                else if (btnType == 4)
                    ToastUtils.showShort(R.string.to_be_continued);
            }
        });
    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvImage.setLayoutManager(layoutManager);
        rvImage.setAdapter(writeImageAdapter);
    }

    @Override
    protected void initListener() {
        setOnClickListener(btnOver, btnAlignLeft, btnAlignCenter, btnAlignRight);
        EditTextChangedListener editTextChangedListener = new EditTextChangedListener(mActivity, etTitle, tvTitleNum, 15, this);
        etTitle.addTextChangedListener(editTextChangedListener);
        writeImageAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initResume() {
        super.initResume();
        if (writeImageAdapter != null)
            writeImageAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_over:
                btnEventPublish();
                break;
            case R.id.btn_align_left:
                etContent.setGravity(Gravity.START | Gravity.TOP);
                alignEnum = EnumCode.ArticleAlignEnum.LEFT;
                break;
            case R.id.btn_align_center:
                etContent.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
                alignEnum = EnumCode.ArticleAlignEnum.CENTER;
                break;
            case R.id.btn_align_right:
                etContent.setGravity(Gravity.END | Gravity.TOP);
                alignEnum = EnumCode.ArticleAlignEnum.RIGHT;
                break;
        }
    }

    @Override
    public void OnWriteTitleListener(String s) {
        etTitle.setText(s);
        etTitle.setSelection(s.length());
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (position == writeImageAdapter.getItemCount() - 1) {
            //打开选择,本次允许选择的数量
            ImagePicker.getInstance().setSelectLimit(maxImgCount - hasSelectPublishImages.size() + 1);
            Intent intent = new Intent(mActivity, ImageGridActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SELECT);
        } else {
            //打开预览
            Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
            intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, new ArrayList<>(hasSelectPublishImages.subList(0, hasSelectPublishImages.size() - 1)));
            intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
            intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
            startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
        }
    }

    /**
     * 发布
     */
    private void btnEventPublish() {
        int realSize = hasSelectPublishImages.size() - 1;
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString();
        if (StringUtils.isEmpty(title)) {
            ToastUtils.showShort("请填写标题");
            return;
        }
        if (StringUtils.isEmpty(content)) {
            ToastUtils.showShort("请填写内容");
            return;
        }
        if (realSize < 1) {
            ToastUtils.showShort("请添加图片");
            return;
        }
        ArrayList<PublishImageItem> publishImageItems = new ArrayList<>();
        for (int i = 0; i < realSize; i++) {
            publishImageItems.add(new PublishImageItem(String.valueOf(i), hasSelectPublishImages.get(i).getPath()));
        }


        publishLoadingDialog.show();

        Intent intent = new Intent(mActivity, UploadArticleImageService.class);
        intent.putExtra(IntentCode.PublishArticle.PUBLISH_NAME, publishName);
        intent.putExtra(IntentCode.PublishArticle.AlIGN, alignEnum == EnumCode.ArticleAlignEnum.LEFT ? "0" : (alignEnum == EnumCode.ArticleAlignEnum.CENTER ? "1" : "2"));
        intent.putExtra(IntentCode.PublishArticle.NICK_NAME, loginSpRes.getNickName());
        intent.putExtra(IntentCode.PublishArticle.UNIQUE_ID, loginSpRes.getUniqueId());
        intent.putExtra(IntentCode.PublishArticle.CONTENT, etContent.getText().toString());
        intent.putExtra(IntentCode.PublishArticle.PUBLISH_TITLE, etTitle.getText().toString());
        intent.putExtra(IntentCode.PublishArticle.PUBLISH_IMAGE_LIST, publishImageItems);
        startService(intent);
    }

    @Override
    protected void initOnDestroy() {
        super.initOnDestroy();
        unregisterReceiver(myReceiver);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                tempWriteImages = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                writeImageAdapter.addData(writeImageAdapter.getItemCount() - 1, tempWriteImages);
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            /*预览图片返回*/
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                tempWriteImages = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (tempWriteImages != null && hasSelectPublishImages.size() > 1) {
                    hasSelectPublishImages.clear();
                    hasSelectPublishImages.add(endImageItem);
                    hasSelectPublishImages.addAll(0, tempWriteImages);
                }
            }
        }
        /*获取压缩后的图片*/
        hasSelectPublishImages = WriteArticleUtil.getLubanResult(getApplication(), hasSelectPublishImages);
    }

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO: This method is called when the BroadcastReceiver is receiving
            String result = intent.getStringExtra(IntentCode.PublishArticle.UPLOAD_IMAGE_RESULT);
            if (result.equals("111"))
                ToastUtils.showShort("BroadcastReceiver");
        }
    }

/*

presenter.requestStrData(Interface.INTERFACE_CODE_NEW_ARTICLE, Interface.INTERFACE_ARTICLE, CacheMode.NO_CACHE,
                new HttpParams("RequestMethod", "NewArticle"),
                new HttpParams("UniqueId", uniqueId),
                new HttpParams("Code", publishName),
                new HttpParams("Title", etTitle.getText().toString()),
                new HttpParams("Content", etContent.getText().toString()),
                new HttpParams("Align", alignEnum == EnumCode.ArticleAlignEnum.LEFT ? "0" : (alignEnum == EnumCode.ArticleAlignEnum.CENTER ? "1" : "2")));

    EventBusUtils.sendStickyEvent(new Event(EventBusCode.ArticleList_Refresh));

   new MaterialDialog.Builder(mActivity).title("发布成功").content("是否前往查看").negativeText("取消").positiveText("确定")
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
        @Override
        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
            mActivity.finish();
        }
    })
            .onPositive(new MaterialDialog.SingleButtonCallback() {
        @Override
        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
            mActivity.finish();
        }
    }).show();*/
}
